import { Component, OnInit } from '@angular/core';
import { NzMessageService, NzModalService, NzFormatEmitEvent } from 'ng-zorro-antd';
import { LocalStorage } from '@core/local.storage';
import { Router } from '@angular/router';
import { HttpParams, HttpHeaders } from '@angular/common/http';
import { _HttpClient } from '@delon/theme';
import { environment } from '../../../../environments/environment';
const responseHeaders = new HttpHeaders().set('Content-Type', 'application/json;charset=UTF-8');

@Component({
    selector: 'app-workplace',
    templateUrl: './workplace.component.html',
    styleUrls: ['./workplace.component.less']
})
export class WorkplaceComponent implements OnInit {
    VC_Name: string;
    ORG_Name: string;
    loadingPerson = true;
    timer: any;
    carousel = ['./assets/banner1.jpg', './assets/banner2.jpg'];
    speedSrc = '';
    temptree: any = [];
    tempids: any = [];
    commonMenuVisible = false;
    commonMenuData: any = [];
    treeNode: any = [];
    defaultCheckedKeys = [];
    loadingMail = true;
    loadingTask = true;
    historyMenuList: any = [];
    lockHeadScroll = { y: window.innerHeight - 350 + 'px' };

    commonMenuDelStyle: any = {
        position: 'absolute',
        right: '5px',
        bottom: '10px',
        color: '#ddd',
        cursor: 'pointer'
    };
    commonMenuBodyStyle = {
        padding: '0'
    };
    commonMenuStyle = {
        width: '16.666%',
        textAlign: 'center',
        padding: '10px 5px',
        position: 'relative',
        cursor: 'pointer'
    };
    gridStyle = {
        width: '16.667%',
        textAlign: 'center',
        padding: '0 14px',
        boxShadow: 'none',
        borderRight: '1px solid #cfcece'
    };
    mailData: any = [];
    backlog: any = [];
    backlogNodata = false;

    constructor(
        public ls: LocalStorage,
        private router: Router,
        private http: _HttpClient,
        private Message: NzMessageService,
        private modalService: NzModalService
    ) { }

    ngOnInit() {
        this.temptree = JSON.parse(this.ls.get('menuTreeData'));
        this.commonMenuView();
        // 访问历史菜单
        const historyTemp = JSON.parse(this.ls.get('historyMenu'));
        for (const item of historyTemp) {
            this.historyMenuList.push({
                'text': item.text.replace(/　/g, ''),
                'link': item.link
            });
        }
        this.waitTask().subscribe(res => {
            this.backlog = res;
            if (!this.backlog.length) {
                this.backlogNodata = true;
            }
            this.loadingTask = false;
        });
        this.unReadMail().subscribe(res => {
            this.mailData = res;
            this.loadingMail = false;
        });
        this.VC_Name = JSON.parse(this.ls.get('loginInfo')).VC_NAME;
        this.ORG_Name = JSON.parse(this.ls.get('loginInfo')).VC_ORG$NAME;
    }
    
    waitTask() {
        const url = environment.apiBase + '/csmis/gateway/task/infos.jwt';
        return this.http.get(url);
    }

    historyMenuClick(link) {
        this.router.navigate([link]);
    }
    // 快捷菜单
    quickMenu() {
        const url = environment.apiBase + '/csmis/gateway/quickmenu/get.jwt';
        return this.http.get(url);
    }
    // 菜单更新
    updateSingleMenu(data) {
        const url = environment.apiBase + '/csmis/gateway/quickmenu/edit.jwt';
        return this.http.post(url, '', { parameJson: data }, { headers: responseHeaders });
    }
    // 删除单个菜单
    delSingleMenu(id) {
        const url = environment.apiBase + '/csmis/gateway/quickmenu/del.jwt';
        const param = { menuid: id };
        return this.http.post(url, '', param, { headers: responseHeaders });
    }
    // 未读邮件
    unReadMail() {
        const url = environment.apiBase + '/csmis/gateway/unreadmail/get.jwt';
        return this.http.get(url);
    }
    // 显示默认常用菜单
    commonMenuView() {
        this.commonMenuData = [];
        for (let l = 0; l < 12; l++) {
            this.commonMenuData.push({
                'id': '',
                'link': '',
                'place': '',
                'name': ''
            });
        }

        this.quickMenu().subscribe((data: any) => {
            this.defaultCheckedKeys = [];
            for (const item of this.temptree) {
                if (item.children) {
                    for (const list of item.children) {
                        if (list.children) {
                            for (const node of list.children) {
                                for (let l = 0; l < data.length; l++) {
                                    if (l > 12) {
                                        break;
                                    }
                                    // id当成link
                                    if (node.id === data[l].menuid) {
                                        this.commonMenuData.unshift({
                                            'id': node.id,
                                            'link': node.link,
                                            'name': node.text,
                                            'place': node.place,
                                            'rename': node.text.length > 8 ? node.text.substring(0, 8) + '...' : node.text
                                        });
                                        this.defaultCheckedKeys.push(node.id);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        });
    }

    // 点击跳转到页面
    commonMenuClick(data) {
        switch (data.place) {
            case 'alain':
                this.router.navigate([data.link]);
                break;
            case 'jsp':
                this.router.navigate(['remotepage/' + data.id]);
                break;
        }
    }

    // 删除菜单
    commonMenuDel(data) {
        this.modalService.confirm({
            nzTitle: '是否删除 <font color="#ff0000">' + data.name + '</font> 菜单？',
            nzOnOk: () => {
                this.delSingleMenu(data.id).subscribe((res: any) => {
                    if (res.msg === 'SUCCESS') {
                        this.Message.create('success', '删除成功!');
                        this.commonMenuView();
                    } else {
                        this.Message.create('error', '删除失败');
                    }
                });
            }
        });
    }

    // 弹出层-菜单列表
    commonMenuAdd() {
        const nodes = [];
        const res = JSON.parse(this.ls.get('menuTreeData'));
        this.treeNode = [];
        this.commonMenuVisible = true;

        res.forEach((item, index1) => {
            nodes.push({
                title: item.text,
                key: item.id,
                children: []
            });
            item.children.forEach((list, index2) => {
                nodes[index1].children.push({
                    title: list.text,
                    key: list.id,
                    children: []
                });
                for (const data of item.children) {
                    nodes[index1].children[index2].children.push({
                        title: data.text,
                        key: data.id,
                        link: data.link,
                        isLeaf: true
                    });
                }
            });
        });

        for (const item of nodes) {
            this.treeNode.push({
                treenodes: [item]
            });
        }
    }

    nzEvent(event: NzFormatEmitEvent, index): void {
        this.tempids[index] = event.nodes;
    }

    commonMenuOk() {
        let temp = [];
        const data = [];
        const user = encodeURI(encodeURI(JSON.parse(this.ls.get('loginInfo')).VC_NUMBER));

        temp = this.formatArray(this.tempids);
        if (temp.length > 12) {
            this.Message.create('error', '最多只能选择12个，请重新添加！');
            return false;
        }
        if (!this.tempids.length) {
            this.commonMenuVisible = false;
        } else {
            for (const item of temp) {
                data.push({
                    usernumber: user,
                    menuid: item
                });
            }
            this.updateSingleMenu(JSON.stringify(data)).subscribe((res: any) => {
                if (res.msg === 'SUCCESS') {
                    this.Message.create('success', '提交成功！');
                    this.commonMenuVisible = false;
                    this.commonMenuView();
                } else {
                    this.Message.create('error', '提交失败！');
                }
            });
        }
    }

    formatArray(thisObject) {
        const temp = [];
        for (const item of thisObject) {
            for (const list of item) {
                if (!list.children.length && list.isChecked) {
                    temp.push(list.origin.key);
                } else {
                    for (const data of list.children) {
                        if (!data.children.length && data.isChecked) {
                            temp.push(data.origin.key);
                        } else {
                            for (const node of data.children) {
                                if (!node.children.length && node.isChecked) {
                                    temp.push(node.origin.key);
                                }
                            }
                        }
                    }
                }
            }
        }
        return temp;
    }

    commonMenuCancel() {
        this.commonMenuVisible = false;
    }

    goMatters(title, menuId) {
        this.router.navigate(title === '材料管理' ? [menuId] : [`/remotepage/${menuId}`]);
    }
}
